from rest_framework import generics, status
from rest_framework.views import APIView, Response
from django.utils.translation import gettext_lazy as _gl

from audit.models import AuditManagement
from lib.rest_api.perms import HasDjangoPermission
from . import serializers
from .. import models

class PublicFileListAPIView(generics.ListAPIView):
    queryset = (
        models.File.objects.select_related("owner").filter(
            object_content_type=None, object_id=None, is_public=True
        ).all()
    )
    serializer_class = serializers.FileSerializer

# TODO different handler for different purpose (such as user resume (self-management),
# public file management)
class DeleteFilesAPIView(APIView):
    def post(self, request, format=None):
        file_ids = request.data
        
        # Validate input format
        if not isinstance(file_ids, list):
            return Response(
                {"error": "Invalid data format, expected a list of file IDs"}, 
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # Check for duplicates
        duplicates = {uuid for uuid in file_ids if file_ids.count(uuid) > 1}
        if duplicates:
            return Response(
                {"error": f"Duplicate file IDs found: {list(duplicates)}"},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # Check existence and permissions
        files = models.File.objects.filter(uuid__in=file_ids)
        found_uuids = set(map(str, files.values_list('uuid', flat=True)))
        missing_uuids = set(file_ids) - found_uuids
        
        if missing_uuids:
            return Response(
                {"error": f"Files not found: {list(missing_uuids)}"},
                status=status.HTTP_404_NOT_FOUND
            )
        
        # Batch delete
        files.delete()
        return Response("ok!", status=status.HTTP_200_OK)

    def get_permissions(self):
        return [HasDjangoPermission(["user.can_manage_resources"])]


class RequestAccessAPIView(APIView):
    def get(self, request, uuid, *args, **kwargs):  # Add uuid parameter here
        user = request.user
        try:
            file = models.File.objects.get(uuid=uuid)
        except models.File.DoesNotExist:
            return Response({"error": _gl("请求访问的文件不存在")}, status=400)

        if file.can_access(user):
            return Response(_gl("用户已经可以访问文件，无需申请"))
        
        user_tag = f"user-{user.id}"
        am, created = AuditManagement.objects.get_or_create_for_object(file, tag=user_tag)

        if not created:
            return Response(_gl("已经提交过申请，请等待审核"))
        
        return Response(_gl("已申请，等待管理员审核"))
